import {Component, ElementRef, Renderer2} from '@angular/core';
import {HomeService} from "../providers/service/home.service";
import {NavigationEnd, Router} from "@angular/router";

@Component({
    selector: 'app-layout',
    templateUrl: './layout.component.html'
})


export class LayoutComponent {

    words: string;//banner中文字
    articleEssence: any;//精华文章
    articleNew: any;//最新文章
    articleClick: any;//点击排行
    showTop: boolean;//展示顶部
    showRight: boolean;//展示右部
    flag:boolean;//图标展示的标识

    constructor(
        private homeService: HomeService,
        private router: Router,
        private render: Renderer2,
        private el: ElementRef
    ) {
        this.words = '';
        this.articleEssence = [];
        this.articleNew = [];
        this.articleClick = [];
        this.showTop = false;
        this.showRight = false;
        this.flag=false;
    }

    ngOnInit() {
        this.homeData();
        this.getArticleNewAndClick();

        //监听路由变化，显示隐藏顶部和右部
        this.router.events
            .subscribe((event) => {

                if (event instanceof NavigationEnd) { // 当导航成功结束时执行

                    this.changeShow(event.url);
                }
            });

        //监听回到顶部按妞
        this.render.listen('window', 'scroll', () => {
            if(!this.flag){
                this.flag=true;
                this.el.nativeElement.querySelector('.top-img').style.display = 'block';
                setTimeout(() => {
                    this.el.nativeElement.querySelector('.top-img').style.display = 'none';
                    this.flag=false;
                }, 3000);
            }

        });

        this.changeShow(this.router.url);
    }

    homeData() {
        this.homeService.home()
            .subscribe(data => {
                if (data.status_code == 200) {
                    this.words = data.result.words;
                    this.articleEssence = data.result.articleEssence;
                }
            });
    }

    //点击排行和最新文章
    getArticleNewAndClick() {
        this.homeService.getArticleNewAndClick()
            .subscribe(data => {
                this.articleNew = data.result.articleNew;
                this.articleClick = data.result.articleClick;
            })
    }

    //决定是否隐藏上部和右部
    changeShow(str: String) {
        if (str.indexOf("/home") != -1) {
            //首页
            this.showTop = true;
            this.showRight = true;
        } else if (str.indexOf("/cate") != -1) {
            //分类页
            this.showRight = true;
            this.showTop = false;
        } else {
            this.showTop = false;
            this.showRight = false;
        }
    }

    //回到顶部
    backTop() {
        document.documentElement.scrollTop=0;
    }


}
